-- cmd_login
-- Create by weism
-- 请求登录指令

-- 内部函数声明
local onConnected;
local onConnectFail;

function Operation.cmd_login(account, ip, port)
    -- 去掉账号头尾空格
    account = AccountM.removeSpace(account);

    LoginM.set_login_stage(LOGIN_STATUS_GS_1);

    if fixHostname then
        ip = fixHostname(ip);
    end

    -- 将信息记录起来
    _G.account = account;
    _G.ip = ip;
    _G.port = port;
    trace("cmd_login", "帐号(%s)请求登录服务器(%s:%d)", account, ip, port);

    if Socket.isConnected() or Socket.isConnecting() then
        trace("cmd_login", "请先断开服务器的连接再登录");
        return false;
    end

    EventMgr.remove("cmd_login", event.NETWORK_CONNECTED);
    EventMgr.remove("cmd_login", event.NETWORK_DISCONNECTED);
    EventMgr.register("cmd_login", event.NETWORK_CONNECTED, onConnected);
    EventMgr.register("cmd_login", event.NETWORK_DISCONNECTED, onConnectFail);

    -- 连接服务器
    Socket.connect(ip, port);

    -- 处理完成
    return true;
end

-- 连接服务器成功后的处理
onConnected = function()
    -- 移除事件关注

    EventMgr.remove("cmd_login", event.NETWORK_CONNECTED)
    EventMgr.remove("cmd_login", event.NETWORK_DISCONNECTED)

    LoginM.set_login_stage(LOGIN_STATUS_GS_2);

    -- 发送auth指令
    Operation.cmd_internal_auth(CFG_TYPE_CONSOLE, _G.account, CFG_SERVICE_GS);

    -- 快捷登陆的情况下，没有连接到cc
    -- 这里先发一条消息获取gs的SupportVersion
    -- 获取完版本后再根据情况发送CMD_LOGIN
    if EXPRESS_LOGIN then
        Communicate.send("CMD_DEBUG_GET_GS_VER", {});
    else
        local auth_key
        local seed
        if not _G.aaaAccountInfo then
            auth_key = 0
            seed     = 0
        else
            auth_key = _G.aaaAccountInfo.auth_key
            seed     = _G.aaaAccountInfo.seed
        end

        -- 发送登录指令
        trace("cmd_login", "发送登录消息");
        Communicate.send("CMD_LOGIN", {
            account  = _G.account,
            auth_key = auth_key,
            seed     = seed,
        });
    end
end

-- 连接服务器失败后的处理
onConnectFail = function()
    trace("cmd_login", "登录失败了");

    -- 移除事件关注
    EventMgr.remove("cmd_login", event.NETWORK_CONNECTED)
    EventMgr.remove("cmd_login", event.NETWORK_DISCONNECTED)
end
